<template>
  <div class="course-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>已选课程</h2>
        </div>
      </template>

      <el-table
        :data="displayedData"
        style="width: 100%"
        :height="tableHeight"
        stripe
        border
        v-loading="Loading"
        element-loading-text="加载中..."
      >

        <el-table-column type="index" label="序号" width="80" align="center"/>
        <el-table-column prop="picture" label="课程图片" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.picture"
              :src="scope.row.picture"
              :preview-src-list="[scope.row.picture]"
              fit="cover"
              style="width: 60px; height: 40px; border-radius: 4px;"
              preview-teleported
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="课程名称" min-width="30" />
        <el-table-column prop="user_id.name" label="授课教师" width="100" />
        <el-table-column prop="content" label="课程内容" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="ChooseCourse(scope.row)"
            >
              选择课程
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="true"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>
<script setup>
import { ElMessage,ElMessageBox } from 'element-plus'
import { computed,onMounted, ref } from 'vue'
import http from "../util/request";
const CourseList = ref([])
const Loading = ref(false)
const tableHeight = ref('600px')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userinfo = ref([])
const userID = ref([])
// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await http.get(`/api/get_user_id/${userinfo.value.username}/`)
    userID.value = res.data
  }catch (error){
    console.error('获取数据失败:', {
      request: error.config.data, // 请求数据
      response: error.response?.data, // 服务器返回的错误信息
      status: error.response?.status, // HTTP 状态码
    })
  }
}
// 获取课程列表
const getCourseList = async () => {
  try {
    Loading.value = true
    const res = await http.get(`/api/stu_course/3`)
    CourseList.value = res.data
    total.value = res.data.length
    // console.log(CourseList.value)
  }catch (error){
    console.error('获取数据失败:', {
      request: error.config.data, // 请求数据
      response: error.response?.data, // 服务器返回的错误信息
      status: error.response?.status, // HTTP 状态码
      headers: error.config.headers,
    })
    ElMessage.error('修改数据失败')
  }finally {
    Loading.value = false
  }
}
// 选择课程
const ChooseCourse = async (row) => {
  console.log(row)
  ElMessageBox.confirm('确定选择该课程吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      Loading.value = true
      const res = await http.get(`/api/stu_course/${row.extral_1}/${userID.value[0]['id']}/`)
      if (res.data.code === 200){
        ElMessage.success('您已拥有该课程')
      }else if (res.data.code === 400){
        try {
          const res = await http.post(`/api/add_stu_course_copy`, {
            name: row.name,
            video: row.video,
            picture: row.picture,
            status: null,
            content: row.content,
            user_id_tea: row.user_id.id,
            user_id_stu_id: userID.value[0]['id'],
            extral_1: row.extral_1,
            extral_2: row.extral_2,
            extral_3: row.extral_3,
          })
          console.log(row)
          console.log(res.data)
          if (res.data.code === 200){
            ElMessage.success('选择课程成功,等待老师通过审核')
          }else {
            ElMessage.error('选择课程失败')
          }
        }catch (error){
          console.error('选择课程失败:', {
            request: error.config.data, // 请求数据
            response: error.response?.data, // 服务器返回的错误信息
            status: error.response?.status, // HTTP 状态码
            headers: error.config.headers,
      })
        }
      }
      getCourseList()
    }catch (error){
      console.error('获取数据失败:', {
        request: error.config.data, // 请求数据
        response: error.response?.data, // 服务器返回的错误信息
        status: error.response?.status, // HTTP 状态码
        headers: error.config.headers,
      })
      ElMessage.error('获取数据失败')
    }finally {
      Loading.value = false
    }
  }).catch((action) => {
    if (action === 'cancel') {
      ElMessage.info('已取消选择课程')
    }else if (action === '') {
      ElMessage.info('已取消选择课程')
    }
  });
}
// 计算当前页面大小
const displayedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return CourseList.value.slice(start, end)
})
// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 当前页改变
const handleCurrentChange = (page) => {
  currentPage.value = page
}
onMounted(async () => {
  userinfo.value = JSON.parse(localStorage.getItem('userinfo'))
  await getUserInfo()
  getCourseList();
})
</script>
<style scoped>

.course-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.box-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 40px;
  background: #f5f7fa;
  color: #909399;
  border-radius: 4px;
}
</style>
